<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加乘车人
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="姓名"  align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="身份证号"  align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.card }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="乘客类型" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.kind | statusFilter">{{ scope.row.kind }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!-- 编辑当前行 -->
          <el-button type="primary" size="mini" @click="handleUpdate(row,$index)">
            编辑
          </el-button>
          <!-- 删除当前行数据 -->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 -->
    <!-- visible：是否显示 Dialog，支持 .sync 修饰符 -->
    <!--  -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
         <!-- 姓名 -->
         <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item> <!-- 姓名 -->
        <el-form-item label="身份证号" prop="card">
          <el-input v-model="temp.card" />
        </el-form-item>
        <!-- 类型 -->
        <el-form-item label="类型" prop="kind">
          <el-select v-model="temp.kind" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 页脚 -->
      <div slot="footer" class="dialog-footer">
        <!-- 取消 -->
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <!-- 确定 -->
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList,deletePassenger,addPassenger,editPassenger } from '@/api/table'
import { mapGetters } from 'vuex'

const calendarTypeOptions = [
  { key: '成人', display_name: '成人票' },
  { key: '儿童', display_name: '儿童票' },
  { key: '学生', display_name: '学生票' },
  { key: '老人', display_name: '老人票' },

]
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        "儿童": 'success',
        "成人": 'gray',
        "学生": 'danger',
        "老人": 'primary'
      }
      return statusMap[status]
    }
  },

  data() {
    return {
      rowid:0,
      oldcard:'',//记录旧值
      dialogStatus:'',//对话框的状态，是添加，还是编辑
      dialogFormVisible: false,//对话框是否可见，初始不可见
      rules: {
        kind: [{ required: true, message: 'kind is required', trigger: 'change' }],
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      calendarTypeOptions,
      temp: {
        username: undefined,
        name:'',
        kind: '',
        card:'',
      },
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      list: null,
      listLoading: true,
      
    }
  },
  created() {
    this.fetchData()
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  methods: {
    resetTemp() {
      this.temp = {
        username: undefined,
        name: '',
        kind: '',
        card: ''
      }
    },
    fetchData() {
      this.listLoading = true
      getList({username: this.name}).then(response => {
       this.list = response.data.data
        this.listLoading = false
      })
    },
  handleDelete(row, index) {
    this.$confirm('此操作将删除该乘车人信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$notify({
      title: '成功',
      message: '删除成功',
      type: 'success',
      duration: 2000
    })
    // 删除数组中指定元素
    this.list.splice(index, 1)
    deletePassenger({card:row.card,user_id:row.user_id})
      }).catch(() => {
        this.$notify.info({
      title: '取消',
      message: '取消删除',
      duration: 2000
    })      
      });
  },
      // 新增前预处理
      handleCreate() {
    // 重设默认值
    this.resetTemp()
    // 设置模态框操作状态为新增
    this.dialogStatus = 'create'
    // 设置模态框可见
    this.dialogFormVisible = true
    // $nextTick：在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法，获取更新后的 DOM。
    // 使用nextTick可立即使用更完的DOM
    this.$nextTick(() => {
      // 移除表单校验结果
      this.$refs['dataForm'].clearValidate()
      // 移除校验结果并重置字段值 (未测试)
      // this.$refs['dataForm'].resetFields()
    })
  },

    // 新增
  createData() {
    // 表单验证
    
    this.$refs['dataForm'].validate((valid) => {
      // 验证通过执行
      
      if (valid) {
        // 模拟id
        this.temp.username = this.name
        // 新增接口
        addPassenger(this.temp).then((response) => {
          // 追加新增数据
          this.temp.id=response.data.data
          this.list.unshift(this.temp)
          // 模态框不可见
          this.dialogFormVisible = false
          // 提示信息
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            // 持续时间
            duration: 2000
          })
        })
      }
    })
  },

  handleUpdate(row,index) {
    // 复制需要更新的内容
    this.rowid=index
    this.oldcard=row.card
    this.temp = Object.assign({}, row) // copy obj
    this.temp.oldcard=this.oldcard
    // 设置操作状态为更新
    this.dialogStatus = 'update'
    // 模态框可见
    this.dialogFormVisible = true
    this.$nextTick(() => {
      // 清除表单验证结果
      this.$refs['dataForm'].clearValidate()
    })
  },
    // 更新数据
  updateData() {
    // 表单验证
    this.$refs['dataForm'].validate((valid) => {
      if (valid) {
        // Object.assign(target, source1, source2)方法用于对象的合并，将源对象（ source ）的所有可枚举属性，复制到目标对象（ target ）。
        // 合并对象
        const tempData = Object.assign({}, this.temp)
        // 执行更新方法
        editPassenger(tempData).then(() => {
          // 查找目标元素，返回元素位置，找不到就返回-1

          const index = this.rowid

          // 通过删除或替换现有元素或者原地添加新的元素来修改数组,
          // 并以数组形式返回被修改的内容。此方法会改变原数组
          this.list.splice(index, 1, this.temp)
          // 模态框不可见
          this.dialogFormVisible = false

          // 消息弹框
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        })
      }
    })
  },

  }
}
</script>
